package com.ms.oschina.base;

import java.util.UUID;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.FragmentManager;

import com.ms.oschina.AppConfig;
import com.ms.oschina.CrashHandler;
import com.ms.oschina.bean.Constants;
import com.ms.oschina.util.PreferenceUtils;
import com.ms.oschina.util.StringUtils;

public class AppContext extends Application {
	private static Context applicationContext;
	private static Looper mainLooper;
	private static Handler mHandler;
	private static AppContext instance;

	public final static String CONF_APP_UNIQUEID = "APP_UNIQUEID";

	public static Context getContext() {
		return applicationContext;
	}

	public static Handler getHandler() {
		return mHandler;
	}

	public static Looper getLooper() {
		return mainLooper;
	}

	/**
	 * 获得当前app运行的AppContext
	 * 
	 * @return
	 */
	public static AppContext getInstance() {
		return instance;
	}

	@Override
	public void onCreate() {
		instance = this;

		Context applicationContext = getApplicationContext();
		this.applicationContext = applicationContext;
		// tid thread uid userid pid process id

		mainLooper = getMainLooper();

		mHandler = new Handler();
		
		CrashHandler ch = CrashHandler.getInstance();
		ch.init(this);
	}

	/**
	 * 获取App安装包信息
	 * 
	 * @return
	 */
	public PackageInfo getPackageInfo() {
		PackageInfo info = null;
		try {
			info = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace(System.err);
		}
		if (info == null)
			info = new PackageInfo();
		return info;
	}

	/**
	 * 获取cookie时传AppConfig.CONF_COOKIE
	 * 
	 * @param key
	 * @return
	 */
	public String getProperty(String key) {
		String res = AppConfig.getAppConfig(this).get(key);
		return res;
	}

	/**
	 * 获取App唯一标识
	 * 
	 * @return
	 */
	public String getAppId() {
		String uniqueID = getProperty(AppConfig.CONF_APP_UNIQUEID);
		if (StringUtils.isEmpty(uniqueID)) {
			uniqueID = UUID.randomUUID().toString();
			setProperty(AppConfig.CONF_APP_UNIQUEID, uniqueID);
		}
		return uniqueID;
	}

	public void setProperty(String key, String value) {
		AppConfig.getAppConfig(this).set(key, value);
	}

	public static boolean isMainThread() {
		return Looper.myLooper() == Looper.getMainLooper();
	}

	public static boolean isLogin() {
		boolean isLogin = PreferenceUtils.getPrefBoolean(getContext(),
				Constants.IS_LOGIN, false);
		return isLogin;
	}

	public static String getUserName() {
		String userName = PreferenceUtils.getPrefString(getContext(),
				Constants.USERNAME, "");
		return userName;
	}

	public static String getUid() {
		String uid = PreferenceUtils
				.getPrefInt(getContext(), Constants.UID, -1) + "";
		return uid;
	}
}